﻿/* Copyright (c) 2001-2009, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
#if !SILVERLIGHT
using System.Data;
#endif
using EffiProz.Core.Lib;
using EffiProz.Core.Store;
using EffiProz.Core.Errors;

namespace EffiProz.Core.DataTypes
{
    public sealed class BooleanType : SqlType
    {
        public static BooleanType booleanType = new BooleanType();

        private BooleanType()
            : base(Types.SQL_BOOLEAN, Types.SQL_BOOLEAN, 0, 0)
        {

        }

        public override int displaySize()
        {
            return 5;
        }

        public override int getAdoTypeCode()
        {
#if !SILVERLIGHT
            return (int)DbType.Boolean;
#else
            return -1;
#endif
        }

        public override String getCSharpClassName()
        {
            return "System.Boolean";
        }

        public override String getNameString()
        {
            return Tokens.T_BOOLEAN;
        }

        public override String getDefinition()
        {
            return Tokens.T_BOOLEAN;
        }

        public override bool isBooleanType()
        {
            return true;
        }

        public override SqlType getAggregateType(SqlType other)
        {

            if (typeCode == other.typeCode)
            {
                return this;
            }

            if (other.isCharacterType())
            {
                return other.getAggregateType(this);
            }

            if (other.isNumberType())
            {
                return other.getAggregateType(this);
            }

            throw Error.error(ErrorCode.X_42562);
        }

        public override SqlType getCombinedType(SqlType other, int operation)
        {

            switch (operation)
            {

                case OpTypes.EQUAL:
                    if (other.isBooleanType())
                    {
                        return this;
                    }
                    break;
            }

            throw Error.error(ErrorCode.X_42562);
        }

        public override int compare(Session session, Object a, Object b)
        {

            if (a == b)
            {
                return 0;
            }

            if (a == null)
            {
                return -1;
            }

            if (b == null)
            {
                return 1;
            }

            bool boola = ((Boolean)a);
            bool boolb = ((Boolean)b);

            return (boola == boolb) ? 0
                                    : (boolb ? -1
                                             : 1);
        }

        public override Object convertToTypeLimits(SessionInterface session, Object a)
        {
            return a;
        }

        public override Object convertToType(SessionInterface session, Object a,
                                    SqlType otherType)
        {

            if (a == null)
            {
                return a;
            }

            switch (otherType.typeCode)
            {

                case Types.SQL_BOOLEAN:
                    return a;

                case Types.SQL_BIT :
                case Types.SQL_BIT_VARYING : {
                    BinaryData b = (BinaryData) a;

                    if (b.bitLength(session) == 1) {
                        return BitMap.isSet(b.getBytes(), 0) ? true
                                                             : false;
                    }

                    break;
                }
                case Types.SQL_CLOB :
                    a = SqlType.SQL_VARCHAR.convertToType(session, a, otherType);

                 //fall through
                    goto case Types.VARCHAR_IGNORECASE;
                case Types.SQL_CHAR:
                case Types.SQL_VARCHAR:
                case Types.VARCHAR_IGNORECASE:
                    {
                        a = ((CharacterType)otherType).trim(session, a, (int)' ',
                                                             true, true);

                        if (((String)a).Equals(Tokens.T_TRUE,StringComparison.OrdinalIgnoreCase))
                        {
                            return true;
                        }
                        else if (((String)a).Equals(Tokens.T_FALSE,StringComparison.OrdinalIgnoreCase))
                        {
                            return false;
                        }
                        else if (((String)a).Equals(Tokens.T_UNKNOWN,StringComparison.OrdinalIgnoreCase))
                        {
                            return null;
                        }

                        break;
                    }
                case Types.SQL_NUMERIC:
                case Types.SQL_DECIMAL:
                    return NumberType.isZero(a) ? false
                                                : true;

                case Types.TINYINT:
                case Types.SQL_SMALLINT:
                case Types.SQL_INTEGER:
                case Types.SQL_BIGINT:
                    {
                        if (Convert.ToInt64(a) == 0)
                        {
                            return false;
                        }
                        else
                        {
                            return true;
                        }
                    }
            }

            throw Error.error(ErrorCode.X_22018);
        }

        /**
         * ResultSet getBoolean support
         */
        public override Object convertToTypeAdo(SessionInterface session, Object a,
                                        SqlType otherType)
        {

            if (a == null)
            {
                return a;
            }

            switch (otherType.typeCode)
            {

                case Types.SQL_BOOLEAN:
                    return a;

                default:
                    if (otherType.isCharacterType())
                    {
                        if ("0".Equals(a))
                        {
                            return true;
                        }
                        else if ("1".Equals(a))
                        {
                            return false;
                        }
                    }

                    return convertToType(session, a, otherType);
            }
        }

        public override Object convertToDefaultType(SessionInterface session, Object a)
        {

            if (a == null)
            {
                return null;
            }

            if (a is Boolean)
            {
                return a;
            }
            else if (a is String)
            {
                return convertToType(session, a, SqlType.SQL_VARCHAR);
            }

            throw Error.error(ErrorCode.X_42561);
        }

        public override String convertToString(Object a)
        {

            if (a == null)
            {
                return null;
            }

            return ((bool)a) ? Tokens.T_TRUE : Tokens.T_FALSE;
        }

        public override String convertToSQLString(Object a)
        {

            if (a == null)
            {
                return Tokens.T_UNKNOWN;
            }

            return ((bool)a) ? Tokens.T_TRUE : Tokens.T_FALSE;
        }

        public override bool canConvertFrom(SqlType otherType)
        {

            return otherType.typeCode == Types.SQL_ALL_TYPES
                   || otherType.isBooleanType() || otherType.isCharacterType()
                   || otherType.isIntegralType()
                   || (otherType.isBitType() && otherType.precision == 1);
        }

        public static BooleanType getBooleanType()
        {
            return booleanType;
        }
    }
}
